//
//  TimedEvent.swift
//  Utility
//
//  Created by 何海涛 on 2017/5/24.
//  Copyright © 2017年 何海涛. All rights reserved.
//

import Foundation

/* the way to cast block to anyobject. */
public typealias Action = ()->Void
public typealias ActionBlock = @convention(block)()->Void
public typealias Closure = (Any?) -> Any?
typealias ObjcClosure = @convention(block)(Any?) -> Any?

extension NSObject {
    
    public static func objcClosure (_ action: @escaping Closure ) -> AnyObject {
        let objcAction: ObjcClosure = action
        return unsafeBitCast(objcAction, to: AnyObject.self)
    }
    
    public static func swiftClosure (_ action: AnyObject?) -> Closure? {
        if let objAction = action,
            let clazz = objAction.classForCoder,
            NSStringFromClass(clazz) == "__NSMallocBlock__"
        {
            let originClosuer: Closure = unsafeBitCast(objAction, to: ObjcClosure.self)
            return originClosuer
        }
        return nil
    }
}
